package edu.hrbu.systemadmin.controller;

import cn.hutool.json.JSONUtil;
import edu.hrbu.systemadmin.entity.YdlUser;
import edu.hrbu.systemadmin.vo.LoginUserVo;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import static edu.hrbu.systemadmin.util.ConstUtil.*;

/**
 * @author 徐登宇
 */
public class BaseController {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    // 获取登录的用户信息
    protected LoginUserVo getLoginUser() {
        HashMap<String, Object> map = new HashMap<>();
        HttpServletRequest request = getRequest();
        // 获取请求头的token
        String token = request.getHeader(HEADER_AUTHORIZATION);
        if (token == null) {
            throw new RuntimeException("该用户未登录！");
        }
        // 获取请求头中的userName
        String tokenKeyPrefix = TOKEN_PREFIX + request.getHeader(HEADER_USERNAME);
        String tokenKey = tokenKeyPrefix + ":" + token;
        // 从redis中获取usercache
        String cacheLoginUserStr = stringRedisTemplate.opsForValue().get(tokenKey);
        if (cacheLoginUserStr == null) {
            throw new RuntimeException("该用户未登录！");
        }

        return JSONUtil.toBean(cacheLoginUserStr, LoginUserVo.class);
    }
}
